﻿using System;
using System.IO;
using System.Reflection;

namespace SharePoint.Orm.Helpers {
	public static class ResourceHelper {
		/// <summary>
		/// If resource starts with "res://" then loads the embedded resource from the fully qualified embedded resource
		/// name (ie with the assembly name)
		/// </summary>
		public static Stream OpenStream(string resource) {
			if (resource.StartsWith("res://")) {
				resource = resource.Substring("res://".Length);
				int firstComma = resource.IndexOf(',');
				string assemblyName = resource.Substring(firstComma + 1);
				Assembly assembly = Assembly.Load(assemblyName);
				Stream templateStream = assembly.GetManifestResourceStream(resource.Substring(0, firstComma));
				if (templateStream == null) {
					throw new NullReferenceException("Could not find '" + resource + "'");
				}
				return templateStream;
			}
			return File.OpenRead(resource);
		}
	}
}
